// import { MqttClient } from 'mqtt/dist/mqtt';
import * as mqtt from 'mqtt/dist/mqtt.min';
import AESUtils from '@/utils/AES.js'
import {
	reactive,
	toRefs
} from 'vue';
import eth from '../../utils/eth'
import { vddsim_protocol, vddsim_port, vddsim_host, vddsim_endpoint, username, password, vddtt_message_password, groupContract, chainId } from '@/utils/config.js'
export default function UseVddsim() {
	const vddsimObj = reactive({
		url: '', // mqtt地址
		topic: [], //订阅地址
		client: null,
		address: '',
		state: 0,
		subscribe: 0
	});

	let topicData = [];
	/**
	 * topics,回调 val: string[], callback: OnMessageCallback
	 */
	function makeTopic({ address, name, type }) {
		let back = name || '#'
		let first = `chat/private`
		let contract = groupContract.toLowerCase()
		if (type == 1) {
			first = 'member'
		}else if(type==2){
			first ='chat/group'
		}
		return `${first}/${contract}-${chainId}/${address}/${back}`
	}
	async function startVddsim(topic, messageCallback, type) {
		let topicName = ''
		if(topic instanceof Array ){
			let arrTopic = []
			topic.forEach(res=>{
				arrTopic.push(makeTopic({ address:res, type }))
			})
			topicName = arrTopic
		}else{
			 topicName = makeTopic({ address:topic, type })
		}
		
		topicData = topicName;
		vddsimObj.topic = topicName;
		const account = await eth.getAccount()
		vddsimObj.address = account;
		//初始化mqtt
		init()
		//设置订阅地址
		link(topicData)
		//消息回调
		vddsimObj.client.on('message', (topic, message) => {
			try {
				console.log('获取监听的主题', topic)
				if (topic.indexOf('member') > -1) {
					messageCallback(topic, vddsimObj.state)
					return
				}
				try {
					var content = message.toString()
					var content1 = AESUtils.decrypt(content, vddtt_message_password)
					var messageObj = JSON.parse(content1)
					console.log(messageObj)
					if (messageObj.c != vddsimObj.address.toLowerCase()) {
						//接收到的对方的消息
						messageCallback(topic, messageObj, vddsimObj.state)
					}
				} catch (e) {

				}

			} catch (error) {

			}

		});
	}

	// 初始化mqtt
	const init = () => {
		try {
			let willTopic = makeTopic({ address:vddsimObj.address,name:'offline', type:1, })
			const options = {
				protocol: vddsim_protocol,
				host: vddsim_host,
				port: vddsim_port,
				endpoint: vddsim_endpoint,
				clean: true, // 保留会话
				// 认证信息
				clientId: '',
				username: username, //用户名 不用的话什么也不用填
				password: password, //密码 不用的话什么也不用填
				keepalive: 10,
				keepAliveInterval: 4, //心跳包
				timeout: 6, //超时时间
				reconnect: true, //自动重连
				will: {
				  topic: willTopic,
				  payload: 'Connection Closed abnormally..!',
				  retain: false,
				  qos: 0,
				},
			};
			const id = vddsimObj.address.toLowerCase() + '_' + parseInt(Math.random() * 1000000)
			options.clientId = id;
			vddsimObj.url = options.protocol + '://' + options.host + ':' + options.port + options.endpoint
			console.log(options)
			vddsimObj.client = mqtt.connect(vddsimObj.url, options);
			vddsimObj.client.on('error', error => {
				console.log('连接错误', error);
				vddsimObj.state = 10001
			});
			vddsimObj.client.on('disconnect', error => {
				console.log('断开连接');
				vddsimObj.state = -1
			})
			vddsimObj.client.on('reconnect', () => {
				console.log('重新连接');
				vddsimObj.state = 1
			});
			vddsimObj.client.on('close', () => {
				console.log('关闭连接');
				vddsimObj.state = 0
			});
		} catch (e) {

		}
	}

	// //取消订阅
	const unsubscribes = (topic) => {
		vddsimObj.client.unsubcsribe(vddsimObj.topic, (error) => {
			if (!error) {
				vddsimObj.subscribe = 0;
			} else {
			}
		});
	}
	const  onMqttMessage =({topic, cb})=> {
		// mitt监听指定topic
		emitter.on(topic, cb)
		// 已建立mqtt链接
		if (mqttClient.connected) {
		  subscribe(topic)
		} else {
		  // 如果还没有连接成功，就监听连接，确保订阅一定能成功
		  mqttClient.on('connect', () => {
			console.log(`mqtt：${process.env.VUE_APP_MQTT}  连接成功...`)
			// 连接成功之后再订阅
			subscribe(topic)
		  })
		}
	  }

	//订阅
	const link = (topic) => {
		if (!vddsimObj.client.connected) {
			vddsimObj.client.on('connect', () => {
				try {
					vddsimObj.state = 2
					const qos = 0;
					if (vddsimObj.subscribe == 0) {
						vddsimObj.client.subscribe(topic, {
							qos
						}, (error, res) => {
							try {
								if (!error) {
									vddsimObj.subscribe = 1;
								} else {
								}
							} catch (error) {

							}

						});
					}
				} catch (error) {

				}
			});
		}
	}

	//收到的消息
	const get = (callback) => {
		// vddsimObj.client.on('message', callback);
	}

	// 结束链接
	const over = () => {
		try {
			if (vddsimObj.client.connected) {
				vddsimObj.client.end(false, () => { })
			}
		} catch (e) {
			// console.log('err2',e)
		}
	}

	//发送
	function send(payload, to, callback, name, type) {
		let content = AESUtils.encrypt(JSON.stringify(payload), vddtt_message_password)
		let lastName = name || 'send'
		const topicName = makeTopic({ address: to, name: lastName, type })
		const qos = 0;

		if (!vddsimObj.client.connected) {
			vddsimObj.client.on('connect', () => {
				try {
					console.log('发送成功', topicName, payload)
					if (vddsimObj.client.connected) {
						vddsimObj.client.publish(topicName, content, {
							qos
						}, (error) => {
							if (error) {
								callback(0)
							} else {
								callback(payload, to)
							}
						})
					} else {
						callback(0)
					}
				} catch (error) {

				}
			})
		} else {
			if (vddsimObj.client.connected) {
				vddsimObj.client.publish(topicName, content, {
					qos
				}, (error) => {
					try {
						if (error) {
							callback(0)
						} else {
							console.log('发送成功2', topicName, payload)
							callback(payload, to)
						}
					} catch (error) {

					}

				})
			} else {
				callback(0)
			}
		}
	}
	// onUnmounted(() => {
	// 	//页面销毁结束订阅
	// })

	return {
		...toRefs(vddsimObj),
		startVddsim,
		send,
		vddsimObj,
		makeTopic,
		unsubscribes,
		init
	};
}